/**
 * 用户模块Store
 */
import {defineStore} from 'pinia'
import {computed,ref} from 'vue'
import {
	loadCategories,getVersion,getIndexMenus
} from './initData'

// 创建Store
export const xasaStore = defineStore('useXasaStore', () => {
	// data
	const categories = ref(null)
	const menus = ref(null)
	//getters
	//const cats = computed(() => {return categories.value})
	// action方法	
	const persistCategories = () => {
		return Promise.all([
			loadCategories(),			
			getVersion('dbname=="xasa-categories"')
			]).then(res=>{
				categories.value = {
					data:res[0].data,
					version:res[1].data.version,
				}
			})
	}
	const persistMenus = () => {
	    return getIndexMenus().then(res=>{
            menus.value = {data:res.data}
        })
    }
	const findMenu = (menu_id) =>{
		for(let i=0;i<menus.value.data.length;i++){
			if(menus.value.data[i].menu_id == menu_id){
				return menus.value.data[i]
			}
		}
		return null
	}
	const findMenuIndex = (menu_id) =>{
		for(let i=0;i<menus.value.data.length;i++){
			if(menus.value.data[i].menu_id == menu_id){
				return i
			}
		}
		return -1
	}
	const findCategoryIndex = (cat_id) =>{
		for(let i=0;i<categories.value.data.length;i++){
			if(categories.value.data[i]._id == cat_id){
				return i
			}
		}
		return -1
	}
	const resetCats = ()=>{
		categories.value = null;
	}
	const resetMenus = ()=>{
		menus.value = null;
	}
	const getCats = async () => {
		if(!categories.value){
			console.log('load cats from cloud.')
			await persistCategories()
		}
		return categories.value;
	}
	const getMenus = async () => {
        if(!menus.value){
            console.log('load menus from cloud.')            
            await persistMenus()           
        }
        return menus.value;        
    }
 	const initFromDb = () => {
		 return Promise.all([
			persistCategories(),
			persistMenus()
		])
	}
	initFromDb();
/* 	const saveProfile = (obj) => {
		menus.value = obj
	} */
	return {
		findCategoryIndex,
		findMenu,
		findMenuIndex,
		initFromDb,
		resetCats,
		resetMenus,
		categories,
		menus,
		//cats,
		getCats,
		getMenus,
		persistCategories,
		persistMenus
	}
}, {
	// 重要：模块必须开启持久化，才会持久化！！！
	// 注意：默认持久化，只在H5端有效，因为默认使用的是localStorage，小程序端不能使用这个API，所以需要重写存取方法，转调给UniApp的持久化方法
	// persist: true,
	persist: {
		// 默认值，就是使用localStorage
		// storage: localStorage
		// 重写存取方法，转调给UniApp
		storage: {
			getItem(key) {
				return uni.getStorageSync(key)
			},
			setItem(key, val) {
				uni.setStorageSync(key, val)
			}
		}
	}
})